package com.ayz.gateway.client;

import lombok.Data;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @ClassName DefaultServerListSwitcher
 * @Description TODO: 默认服务端地址的选择器
 * 默认使用轮询算法在 服务器列表中 选择一个地址返回
 * @Author 快乐的星球
 * @Date 2023/5/20 23:17
 * @Version 1.0
 **/
@Data
public class DefaultServerListSwitcher implements ServerListSwitcher{
    /**
     * 服务端地址列表
     */
    private List<String> serverAddressList;
    /**
     * 轮询自增的下标
     */
    private final AtomicInteger index=new AtomicInteger(0);
    /**
     * 当前选中的服务端地址
     */
    private String currentServer;

    public DefaultServerListSwitcher(List<String> serverAddressList) {
        this.serverAddressList = serverAddressList;
    }

    public DefaultServerListSwitcher() {
        this.serverAddressList=new ArrayList<>();
    }

    public void addServerAddress(String serverAddress){
        this.serverAddressList.add(serverAddress);
    }

    public void addServerAddressList(List<String> serverAddressList){
        this.serverAddressList.addAll(serverAddressList);
    }
    @Override
    public String currentServer() {
        return this.currentServer;
    }

    @Override
    public String nextServer() {
        if(serverAddressList==null || serverAddressList.isEmpty()){
            return null;
        }
        int size=serverAddressList.size();
        String currentServerAddress=getServerAddressList().get((index.getAndIncrement())%size);
        setCurrentServer(currentServerAddress);
        return currentServerAddress;
    }
}
